﻿using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;

namespace Glorysoft.EAP.EAPClient.Common
{
    public class KeyToCommandExtension :MarkupExtension
    {
        DependencyObject Dependencyobject = new DependencyObject();
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(KeyToCommandExtension));
        public ICommand Command
        {
            get
            {
                return (ICommand)Dependencyobject.GetValue(CommandProperty);
            }
            set
            {
                Dependencyobject.SetValue(CommandProperty, value);
            }
        }
        private void KeyEvent(object sender, KeyEventArgs e)
        {
            //if (Key != Key.None ) return;
            var target = (FrameworkElement)sender;
            if (Command != null && Command.CanExecute(null))
                Command.Execute(null);
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (Command==null)
                throw new InvalidOperationException("Command not set");
            var targetProvider = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
            if (!(targetProvider.TargetObject is FrameworkElement))
                throw new InvalidOperationException("Target object must be FrameworkElement");
            if (!(targetProvider.TargetProperty is EventInfo))
                throw new InvalidOperationException("Target property must be event");
            return Delegate.CreateDelegate(typeof(KeyEventHandler), this, "KeyEvent");
        }
    }
}

